package com.ftl.search.common.config;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.common.utils.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ftl.search.common.property.SearchNacosProperties;
import com.ftl.search.model.SearchDefinition;
import com.ftl.search.service.SearchConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.Executor;

@Slf4j
@Component
@RefreshScope
public class SearchInitConfig {

    @Resource
    private SearchNacosProperties searchNacosProperties;

    @Resource
    private NacosConfigProperties nacosConfigProperties;

    @Resource
    private ConfigService configService;

    @Resource
    private SearchConfigService searchConfigService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @PostConstruct
    public void init() {
        log.info("开始加载搜索配置...");
        try {
            String initConfigInfo = configService.getConfigAndSignListener(searchNacosProperties.getDataId(), searchNacosProperties.getGroup(), nacosConfigProperties.getTimeout(), new Listener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }

                @Override
                public void receiveConfigInfo(String configInfo) {
                    if (StringUtils.isNotEmpty(configInfo)) {
                        log.info(configInfo);
                        SearchDefinition searchDefinition = null;
                        try {
                            searchDefinition = objectMapper.readValue(configInfo, new TypeReference<SearchDefinition>() {});
                        } catch (JsonProcessingException exception) {
                            log.error("解析搜索配置出错", exception);
                        }
                        searchConfigService.save(searchDefinition);
                    } else {
                        log.warn("当前没有搜索配置");
                    }
                }
            });
            log.info("获取搜索配置:\r\n{}", initConfigInfo);
            if (StringUtils.isNotEmpty(initConfigInfo)) {
                SearchDefinition searchDefinition = objectMapper.readValue(initConfigInfo, new TypeReference<SearchDefinition>() {});
                searchConfigService.save(searchDefinition);
            } else {
                log.warn("当前没有搜索配置");
            }
        } catch (Exception e) {
            log.error("加载搜索配置出错", e);
        } finally {
            log.info("加载搜索配置结束...");
        }
    }


}
